<template>
  <div class="mobile-product-list">
    <!-- 筛选表单 -->
    <div class="filter-form">
      <div class="update-time">最近更新时间：{{ refreshTime }}</div>

      <div class="type-selector">
        <el-radio-group v-model="goodsType" @change="changeGoodsType" size="small">
          <el-radio-button label="spu">大商品纬度</el-radio-button>
          <el-radio-button label="sku">子款式纬度</el-radio-button>
        </el-radio-group>
      </div>

      <el-form size="small" label-width="80px">
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="dataDates"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy/MM/dd"
            style="width: 100%"
            :picker-options="pickerOptions"
            @change="changeDataTime">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="产品系列">
          <el-select v-model="searchParams.seriesId" placeholder="请选择产品系列" clearable style="width: 100%">
            <el-option
              v-for="item in seriesList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称/SKU">
          <el-input v-model="searchParams.searchText" placeholder="请输入商品名称或SKU" clearable></el-input>
        </el-form-item>
        <el-form-item label="排序">
          <el-select v-model="searchParams.orderField" placeholder="请选择排序方式" clearable style="width: 100%">
            <el-option label="订单数量" :value="1"></el-option>
            <el-option label="商品销售量" :value="2"></el-option>
            <el-option label="商品销售总价" :value="3"></el-option>
            <el-option label="商品净销售额" :value="4"></el-option>
            <el-option label="加购数量" :value="5"></el-option>
            <el-option label="浏览量" :value="6"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchHandler" style="margin-right: 10px">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 商品数据列表 -->
    <div class="product-list">
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      <div v-else-if="productList.length === 0" class="empty-container">
        <empty />
      </div>
      <div v-else>
        <div v-for="(item, index) in productList" :key="index" class="product-item" @click="goToProductDetail(item.spuId)">
          <div class="product-header">
            <el-image class="product-image" :src="item.goodsImage" fit="contain"></el-image>
            <div class="product-name">{{ item.goodsName }}</div>
          </div>

          <div class="product-info">
            <!-- SPU 商品信息 -->
            <template v-if="goodsType === 'spu'">
              <div class="info-item">
                <span class="label">商品类型:</span>
                <span class="value">{{ formatSpuType(item.spuType) }}</span>
              </div>
              <div class="info-item">
                <span class="label">总订单量:</span>
                <span class="value">{{ item.orderQty }}</span>
              </div>
              <div class="info-item">
                <span class="label">销量(件):</span>
                <span class="value">{{ item.salesQty }}</span>
              </div>
              <div class="info-item">
                <span class="label">销售总额:</span>
                <span class="value">{{ formatCurrency(item.totalSales) }}</span>
              </div>
              <div class="info-item">
                <span class="label">净销售额:</span>
                <span class="value">{{ formatCurrency(item.netSales) }}</span>
              </div>
              <div class="info-item">
                <span class="label">浏览量:</span>
                <span class="value">{{ item.scanCount || 0 }}</span>
              </div>
              <div class="info-item">
                <span class="label">加购数:</span>
                <span class="value">{{ item.cartCount || 0 }}</span>
              </div>
              <div class="info-item">
                <span class="label">转化率:</span>
                <span class="value">{{ formatPercent(item.translatePercent) }}</span>
              </div>
            </template>

            <!-- SKU 商品信息 -->
            <template v-else>
              <div class="info-item">
                <span class="label">SKU:</span>
                <span class="value">{{ item.goodsCode }}</span>
              </div>
              <div class="info-item">
                <span class="label">总订单量:</span>
                <span class="value">{{ item.orderQty }}</span>
              </div>
              <div class="info-item">
                <span class="label">销量(件):</span>
                <span class="value">{{ item.salesQty }}</span>
              </div>
              <div class="info-item">
                <span class="label">销售总额:</span>
                <span class="value">{{ formatCurrency(item.totalSales) }}</span>
              </div>
              <div class="info-item">
                <span class="label">净销售额:</span>
                <span class="value">{{ formatCurrency(item.netSales) }}</span>
              </div>
            </template>
          </div>
        </div>

        <!-- 分页组件 -->
        <div class="pagination-container">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageParams.page"
            :page-sizes="[20, 30, 50]"
            :page-size="pageParams.pageSize"
            layout="total, prev, pager, next"
            :small="true"
            :total="total">
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getSpuSalesPage, getSkuSalesPage } from '@/api/stat-goods';
import { getSeriesList } from '@/api/goods';
import { mapGetters } from 'vuex';
import { currency, utcFormat } from '@/utils/filters';

export default {
    name: 'MobileProductList',
    props: {
        siteId: {
            type: [String, Number],
            required: true
        }
    },
    data () {
        return {
            loading: false,
            productList: [],
            total: 0,
            refreshTime: '',
            goodsType: 'spu',
            dataDates: [],
            seriesList: [],
            pickerOptions: {
                firstDayOfWeek: 1,
                shortcuts: [{
                    text: '最近一周',
                    onClick (picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick (picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setMonth(start.getMonth() - 1);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近三个月',
                    onClick (picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setMonth(start.getMonth() - 3);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            },
            searchParams: {
                seriesId: null,
                searchText: '',
                orderField: null
            },
            pageParams: {
                siteId: this.siteId,
                page: 1,
                pageSize: 20,
                startTime: null,
                finishTime: null
            }
        };
    },
    computed: {
        ...mapGetters([
            'timeZone',
            'siteList'
        ]),
        currencySymbol () {
            const info = this.siteList.find(res => res.id === Number(this.siteId));
            return info ? info.currencySymbol : '$';
        }
    },
    created () {
        this.initData();
        this.fetchSeriesList();
        this.fetchData();
    },
    methods: {
        initData () {
            let now = new Date();
            let tempMonth = (100 + now.getMonth() + 1).toString().substring(1);
            let tempDay = (100 + now.getDate()).toString().substring(1);
            let tempDate = now.getFullYear() + '/' + tempMonth + '/' + tempDay;
            this.dataDates = [tempDate, tempDate];
            this.pageParams.startTime = new Date(tempDate + ' 00:00:00 UTC' + this.timeZone).getTime();
            this.pageParams.finishTime = new Date(tempDate + ' 23:59:59 UTC' + this.timeZone).getTime();
        },
        fetchSeriesList () {
            getSeriesList({ siteId: this.siteId }).then(res => {
                this.seriesList = res.data || [];
            });
        },
        fetchData () {
            this.loading = true;

            const params = {
                ...this.pageParams,
                ...this.searchParams
            };

            if (this.goodsType === 'spu') {
                getSpuSalesPage(params).then(res => {
                    let tempTime = res.data.refreshTime;
                    if (tempTime) {
                        this.refreshTime = utcFormat(tempTime, 'YYYY-MM-DD HH:mm:ss', this.timeZone);
                    } else {
                        this.refreshTime = '';
                    }

                    this.productList = res.data.records || [];
                    this.total = res.data.totalElements || 0;

                    // 处理数据
                    this.productList.forEach(val => {
                        if (!val.scanCount) { val.scanCount = 0; }
                        if (!val.translatePercent) { val.translatePercent = 0; }
                    });

                    this.loading = false;
                }).catch(() => {
                    this.loading = false;
                });
            } else {
                getSkuSalesPage(params).then(res => {
                    let tempTime = res.refreshTime;
                    if (tempTime) {
                        this.refreshTime = utcFormat(tempTime, 'YYYY-MM-DD HH:mm:ss', this.timeZone);
                    } else {
                        this.refreshTime = '';
                    }

                    this.productList = res.records || [];
                    this.total = res.totalElements || 0;
                    this.loading = false;
                }).catch(() => {
                    this.loading = false;
                });
            }
        },
        changeGoodsType () {
            this.pageParams.page = 1;
            this.fetchData();
        },
        changeDataTime () {
            if (!this.dataDates || this.dataDates.length <= 0) {
                this.initData();
            } else {
                this.pageParams.startTime = new Date(this.dataDates[0].replace(/-/g, '/') + ' 00:00:00 UTC' + this.timeZone).getTime();
                this.pageParams.finishTime = new Date(this.dataDates[1].replace(/-/g, '/') + ' 23:59:59 UTC' + this.timeZone).getTime();
            }
        },
        searchHandler () {
            this.pageParams.page = 1;
            this.fetchData();
        },
        resetForm () {
            this.initData();
            this.searchParams = {
                seriesId: null,
                searchText: '',
                orderField: null
            };
            this.pageParams.page = 1;
            this.pageParams.pageSize = 10;
            this.fetchData();
        },
        handleSizeChange (val) {
            this.pageParams.pageSize = val;
            this.fetchData();
        },
        handleCurrentChange (val) {
            this.pageParams.page = val;
            this.fetchData();
        },
        formatCurrency (amount) {
            return currency(amount, this.currencySymbol);
        },
        formatPercent (value) {
            return currency(value, '%', 2, {
                thousandsSeparator: '',
                symbolOnLeft: false
            });
        },
        formatSpuType (type) {
            const types = {
                '0': '普通商品',
                '1': '定制商品'
            };
            return types[type] || '未知类型';
        },
        goToProductDetail (id) {
            this.$router.push({ name: 'goods-detail', params: { id } });
        }
    }
};
</script>

<style lang="scss" scoped>
.mobile-product-list {
  padding: 10px 0;

  .filter-form {
    background-color: #fff;
    padding: 15px;
    border-radius: 4px;
    margin-bottom: 15px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .update-time {
      margin-bottom: 15px;
      color: #606266;
      font-size: 14px;
    }

    .type-selector {
      margin-bottom: 15px;
    }
  }

  .product-list {
    .loading-container, .empty-container {
      padding: 20px;
      background-color: #fff;
      border-radius: 4px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }

    .product-item {
      background-color: #fff;
      border-radius: 4px;
      padding: 15px;
      margin-bottom: 15px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

      .product-header {
        display: flex;
        align-items: center;
        padding-bottom: 10px;
        border-bottom: 1px solid #ebeef5;

        .product-image {
          width: 60px;
          height: 60px;
          margin-right: 10px;
          border-radius: 4px;
          border: 1px solid #ebeef5;
        }

        .product-name {
          flex: 1;
          font-weight: bold;
          color: #409EFF;
          font-size: 14px;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }
      }

      .product-info {
        padding: 10px 0;

        .info-item {
          display: flex;
          margin-bottom: 8px;

          .label {
            width: 100px;
            color: #606266;
          }

          .value {
            flex: 1;
            color: #303133;
          }
        }
      }
    }

    .pagination-container {
      text-align: center;
      margin-top: 20px;
      padding: 15px;
      background-color: #fff;
      border-radius: 4px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }
  }
}

@media screen and (max-width: 768px) {
  .mobile-product-list {
    .pagination-container {
      .el-pagination {
        white-space: normal;

        .el-pagination__sizes {
          margin-top: 10px;
        }
      }
    }
  }
}
</style>
